package cn.congine.wizarpos.mall.dao.hibernate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import cn.congine.wizarpos.mall.dao.WxShoppingCartDao;
import cn.congine.wizarpos.mall.model.WxShoppingCart;
import cn.congine.wizarpos.mall.utils.Function;

@Repository("wxShoppingCartDao")
public class WxShoppingCartDaoHibernate extends
		GenericDaoHibernate<WxShoppingCart> implements WxShoppingCartDao {

	public WxShoppingCartDaoHibernate() {
		super(WxShoppingCart.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<WxShoppingCart> getWxShoppingCartByOpenId(String openId) {
		Query query = getSession().createQuery(
				"from WxShoppingCart where openId=:openId ").setParameter(
				"openId", openId);
		return (List<WxShoppingCart>) query.list();
	}

	@Override
	public WxShoppingCart getWxShoppingCart(String openId, String mid) {
		Query query = getSession().createQuery(
				"from WxShoppingCart where openId=:openId and mid =:mid");
		Map<String, Object> wsCart = new HashMap<String, Object>();
		wsCart.put("openId", openId);
		wsCart.put("mid", mid);
		query.setProperties(wsCart);
		return (WxShoppingCart) query.uniqueResult();
	}

	@Override
	public WxShoppingCart getWxShoppingCartByMId(String mid) {
		Query query = getSession().createQuery(
				"from WxShoppingCart where mid=:mid").setParameter("mid", mid);
		return (WxShoppingCart) query.uniqueResult();
	}

	@Override
	public WxShoppingCart save(WxShoppingCart obj) {
		String uuid = Function.getUid();
		obj.setId(uuid);
		String sql = "INSERT INTO wx_shopping_cart (id, open_id, create_time, mid, cart_type) VALUES (?,?,?,?,?)";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query query = this.getSession().createSQLQuery(sql);

		query.setString(0, obj.getId());
		query.setString(1, obj.getOpenId());
		query.setLong(2, obj.getCreateTime());
		query.setString(3, obj.getMid());
		query.setString(4, obj.getCartType());

		query.executeUpdate();
		return obj;
	}

	@Override
	public void update(WxShoppingCart obj) {
		String sql = "UPDATE wx_shopping_cart SET open_id = ?, create_time = ?,"
				+ " cart_type = ? WHERE id = ? and mid = ?";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query query = this.getSession().createSQLQuery(sql);

		query.setString(0, obj.getOpenId());
		query.setLong(1, obj.getCreateTime());
		query.setString(2, obj.getCartType());
		query.setString(3, obj.getId());
		query.setString(4, obj.getMid());
		
		query.executeUpdate();
	}

	@Override
	public void remove(String id, String mid) {
		String hql = "delete From WxShoppingCart where id = ? and mid = ?";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createQuery(hql);
		q.setString(0, id);
		q.setString(1, mid);
		q.executeUpdate();
	}
}
